﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.Collections.Generic;
using System.Linq;

#endregion

namespace ScrumTable.Common.Collections
{
    /// <summary>
    /// Specifies a range of values and a selected value which may be within
    /// this range.
    /// </summary>
    public class ValueRange<T> : IEnumerable<T>, IEquatable<ValueRange<T>>
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        private const string ValueSeparator = " # ";

        private readonly List<T> _values;
        private readonly string _joinedValues;
        private readonly int _selectedIndex;
        private readonly T _selectedValue;

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        /// <summary>
        /// Gets the value at the given chain index.
        /// </summary>
        /// <param name="index">Index of the value to retrieve.</param>
        /// <returns>Returns the retrieved value.</returns>
        public T this[int index]
        {
            get
            {
                PreCondition.AssertInRange(-1, _values.Count, index, "index");
                return _values[index];
            }
        }

        /// <summary>
        /// Gets the number of values stored in the current collection.
        /// </summary>
        public int Count
        {
            get { return _values.Count; }
        }

        /// <summary>
        /// Returns true if the current value chain is empty.
        /// </summary>
        public bool IsEmpty
        {
            get { return (Count == 0); }
        }

        /// <summary>
        /// Returns true if the selected value is within the
        /// current value range.
        /// </summary>
        public bool SelectedValueWithinRange
        {
            get { return (SelectedIndex != -1); }
        }

        /// <summary>
        /// Gets the selected value within the range.
        /// </summary>
        public T SelectedValue
        {
            get { return _selectedValue; }
        }

        /// <summary>
        /// Gets the selected index within the range.
        /// </summary>
        public int SelectedIndex
        {
            get { return _selectedIndex; }
        }

        /// <summary>
        /// Returns the current instance data as on single string value.
        /// </summary>
        public string SingleValue
        {
            get { return _joinedValues; }
        }

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new ValueChain instance with the specified data.
        /// </summary>
        public ValueRange(IEnumerable<T> values, T selectedValue)
        {
            _values = new List<T>(values);
            _joinedValues = _values.ToString(selectedValue, ValueSeparator);
            _selectedValue = selectedValue;
            _selectedIndex = -1;

            for (int i = 0; i < _values.Count; ++i)
            {
                if (Equals(_values[i], selectedValue))
                {
                    _selectedIndex = i;
                    break;
                }
            }
        }

        /// <summary>
        /// Creates a new ValueChain instance with the specified data.
        /// </summary>
        public ValueRange()
            : this(new T[0], default(T))
        {
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Parses the given string as a ValueRange&lt;string&gt;.
        /// </summary>
        /// <param name="toParse">Specifies the string to parse.</param>
        /// <returns>Returns the parse string data as new object.</returns>
        public static ValueRange<string> Parse(string toParse)
        {
            PreCondition.AssertNotNullOrEmpty(toParse, "toParse");
            
            string[] parseData = toParse.Split(new[] { ValueSeparator }, StringSplitOptions.None);
            string current = null;

            foreach (var data in parseData)
            {
                if (data != null && data.StartsWith("(") && data.EndsWith(")"))
                {
                    current = data;
                    break;
                }
            }
            return new ValueRange<string>(parseData, current);
        }

        /// <summary>
        /// Implements the operator ==.
        /// </summary>
        /// <param name="left">Specifies the left object.</param>
        /// <param name="right">Specifies the right object.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator ==(ValueRange<T> left, ValueRange<T> right)
        {
            // If both are null, or both are same instance, return true.
            if (ReferenceEquals(left, right))
            {
                return true;
            }

            // If one is null, but not both, return false.
            if ((object)left == null || (object)right == null)
            {
                return false;
            }

            // Return true if the fields match:
            return left.Equals(right);
        }

        /// <summary>
        /// Implements the operator !=.
        /// </summary>
        /// <param name="left">Specifies the left object.</param>
        /// <param name="right">Specifies the right object.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator !=(ValueRange<T> left, ValueRange<T> right)
        {
            return !(left == right);
        }

        /// <summary>
        /// Determines whether the specified IDataObject is equal to the current object.
        /// </summary>
        /// <param name="toCompare">Parameter to check.</param>
        /// <returns>Returns true if the objects are equal.</returns>
        public override bool Equals(object toCompare)
        {
            // If parameter cannot be cast to DomainBase return false.
            return Equals(toCompare as ValueRange<T>);
        }

        /// <summary>
        /// Determines whether the specified IDataObject is equal to the current object.
        /// </summary>
        /// <param name="obj">Parameter to check.</param>
        /// <returns>Returns true if the objects are equal.</returns>
        public bool Equals(ValueRange<T> obj)
        {
            // If parameter is null return false:
            if ((object)obj == null) // force compiler to use Object::operator==()
                return false;

            if (obj._values.Count != _values.Count)
                return false;

            for (int i = 0; i < _values.Count; ++i)
            {
                if (!Equals(obj._values[i], _values[i]))
                    return false;
            }
            return true;
        }

        /// <summary>
        /// Returns the hash code for this IDataObject.
        /// </summary>
        /// <returns>Returns the computed hash value.</returns>
        public override int GetHashCode()
        {
            return _joinedValues.GetHashCode();
        }

        /// <summary>
        /// Tries to retrieve the given value.
        /// </summary>
        /// <param name="index">Index of the value to retrieve.</param>
        /// <returns>Returns the retrieved value or an empty string.</returns>
        public T TryGetValue(int index)
        {
            if (index > -1 && index < _values.Count)
                return _values[index];
            return default(T);
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return string.Format("{0} [{1}]", base.ToString(), _joinedValues);
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
        /// </returns>
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return ((IEnumerable<string>)this).GetEnumerator();
        }

        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
        /// </returns>
        public IEnumerator<T> GetEnumerator()
        {
            return _values.GetEnumerator();
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion
    }
}